//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"context"

	"atomgit.com/openlinksaas/mongo-proxy/gen_code"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type DatabaseApiImpl struct{}

func (s *DatabaseApiImpl) DatabaseListPost(ctx context.Context, req gen_code.DatabaseListPostRequest) (gen_code.ImplResponse, error) {
	if req.Token != token {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "wrong token",
			},
		}, nil
	}
	infoItem, ok := clientMap.Load(req.Id)
	if !ok {
		return gen_code.ImplResponse{
			Code: 200,
			Body: req.Id,
		}, nil
	}
	info := infoItem.(*ClientInfo)
	if info.Database != "" {
		return gen_code.ImplResponse{
			Code: 200,
			Body: []string{info.Database},
		}, nil
	}
	client := info.client.(*mongo.Client)
	names, err := client.ListDatabaseNames(ctx, bson.M{})
	if err != nil {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: err.Error(),
			},
		}, nil
	}
	return gen_code.ImplResponse{
		Code: 200,
		Body: names,
	}, nil
}
